const { getCoupons, receiveCouponById, checkCouponAvailability, markCouponAsUsed } = require('../models/Coupon');

const getAllCoupons = async (req, res) => {
    try {
        const coupons = await getCoupons();
        res.json({
            success: true,
            code: 200,
            data: coupons,
            message: '获取优惠券列表成功'
        });
    } catch (error) {
        console.error('[COUPON] 获取优惠券列表失败:', error);
        res.status(500).json({ 
            success: false, 
            code: 500, 
            message: '服务器内部错误' 
        });
    }
};

const receiveCoupon = async (req, res) => {
    try {
        const userId = req.user.userId;
        const { couponId } = req.body;
        
        if (!couponId) {
            return res.status(400).json({
                success: false,
                code: 400,
                message: '缺少优惠券ID'
            });
        }
        
        // 检查优惠券是否可领取
        const couponAvailable = await checkCouponAvailability(couponId);
        if (!couponAvailable) {
            return res.status(400).json({
                success: false,
                code: 1001,
                message: '优惠券不可领取或已过期'
            });
        }
        
        // 领取优惠券
        const result = await receiveCouponById(userId, couponId);
        
        res.json({
            success: true,
            code: 200,
            message: '领取优惠券成功',
            data: { id: result.insertId }
        });
    } catch (error) {
        console.error('[COUPON] 领取优惠券失败:', error);
        
        // 处理重复领取的错误
        if (error.code === 'ER_DUP_ENTRY') {
            return res.status(400).json({
                success: false,
                code: 1002,
                message: '您已领取过该优惠券'
            });
        }
        
        res.status(500).json({
            success: false,
            code: 500,
            message: '服务器内部错误'
        });
    }
};

const useCoupon = async (req, res) => {
    try {
        const userId = req.user.userId;
        const { userCouponId, orderId } = req.body;
        
        if (!userCouponId || !orderId) {
            return res.status(400).json({
                success: false,
                code: 400,
                message: '缺少必要参数'
            });
        }
        
        // 标记优惠券为已使用
        const result = await markCouponAsUsed(userId, userCouponId, orderId);
        
        if (result.affectedRows === 0) {
            return res.status(400).json({
                success: false,
                code: 1003,
                message: '优惠券不存在或已被使用'
            });
        }
        
        res.json({
            success: true,
            code: 200,
            message: '使用优惠券成功'
        });
    } catch (error) {
        console.error('[COUPON] 使用优惠券失败:', error);
        res.status(500).json({
            success: false,
            code: 500,
            message: '服务器内部错误'
        });
    }
};

module.exports = { getAllCoupons, receiveCoupon, useCoupon };